package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.core.domain.zzw.BO.SelectAverageBO;
import com.ruoyi.common.core.domain.zzw.TIndicatorsInfo;
import com.ruoyi.common.core.domain.zzw.TSafenessIndex;
import com.ruoyi.common.core.domain.zzw.VO.*;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.TIndicatorsInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TSafenessIndexMapper;
import com.ruoyi.system.service.ITSafenessIndexService;
import com.fasterxml.jackson.databind.ObjectMapper;

import static org.apache.commons.lang3.ObjectUtils.isEmpty;

/**
 * 平安指数Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-03
 */
@Service
public class TSafenessIndexServiceImpl extends ServiceImpl<TSafenessIndexMapper, TSafenessIndex> implements ITSafenessIndexService
{
    @Autowired
    private TSafenessIndexMapper tSafenessIndexMapper;

    @Autowired
    private  TIndicatorsInfoMapper indicatorsInfoMapper;
    /**
     * 查询平安指数
     *
     * @param cSafenessId 平安指数主键
     * @return 平安指数
     */
    @Override
    public TSafenessIndex selectTSafenessIndexByCSafenessId(Long cSafenessId)
    {
        return tSafenessIndexMapper.selectTSafenessIndexByCSafenessId(cSafenessId);
    }

    /**
     * 查询平安指数列表
     *
     * @param tSafenessIndex 平安指数
     * @return 平安指数
     */
    @Override
    public List<TSafenessIndex> selectTSafenessIndexList(TSafenessIndex tSafenessIndex)
    {
        return tSafenessIndexMapper.selectTSafenessIndexList(tSafenessIndex);
    }

    /**
     * 新增平安指数
     *
     * @param tSafenessIndex 平安指数
     * @return 结果
     */
    @Override
    public int insertTSafenessIndex(TSafenessIndex tSafenessIndex)
    {
        return tSafenessIndexMapper.insertTSafenessIndex(tSafenessIndex);
    }

    /**
     * 修改平安指数
     *
     * @param tSafenessIndex 平安指数
     * @return 结果
     */
    @Override
    public int updateTSafenessIndex(TSafenessIndex tSafenessIndex)
    {
        return tSafenessIndexMapper.updateTSafenessIndex(tSafenessIndex);
    }

    /**
     * 批量删除平安指数
     *
     * @param cSafenessIds 需要删除的平安指数主键
     * @return 结果
     */
    @Override
    public int deleteTSafenessIndexByCSafenessIds(Long[] cSafenessIds)
    {
        return tSafenessIndexMapper.deleteTSafenessIndexByCSafenessIds(cSafenessIds);
    }

    /**
     * 删除平安指数信息
     *
     * @param cSafenessId 平安指数主键
     * @return 结果
     */
    @Override
    public int deleteTSafenessIndexByCSafenessId(Long cSafenessId)
    {
        return tSafenessIndexMapper.deleteTSafenessIndexByCSafenessId(cSafenessId);
    }

    @Override
    public List<TSafenessIndex> ByRegionTop(TSafenessIndex tSafenessIndex) {
        return tSafenessIndexMapper.ByRegionTop(tSafenessIndex);
    }

    @Override
    public List<TSafenessIndex> BycRegionId(TSafenessIndex tSafenessIndex) {
        if (tSafenessIndex.getcRegionId()==null){
            tSafenessIndex.setcRegionId(1L);
        }
        if (StringUtils.isEmpty(tSafenessIndex.getcYear())){
            tSafenessIndex.setcYear("2023");
        }
        if (StringUtils.isEmpty(tSafenessIndex.getcMonth())){
            tSafenessIndex.setcMonth("10");
        }
        return tSafenessIndexMapper.BycRegionId(tSafenessIndex);
    }

    @Override
    public List<TSafenessIndex> BycPid(TSafenessIndex tSafenessIndex) {
        return tSafenessIndexMapper.BycPid(tSafenessIndex);
    }

    @Override
    public List<TIndicatorsList> ById(TSafenessIndex tSafenessIndex) {
        List<TIndicatorsInfo> list = indicatorsInfoMapper.BycSafenessId(tSafenessIndex);
        return getLists(list);
    }

    @Override
    public List<TIndicatorsList> safBycRegId(Long id) {
        List<TIndicatorsInfo> list = indicatorsInfoMapper.safBycRegId(id);
        return getLists(list);
    }

    private static List<TIndicatorsList> getLists(List<TIndicatorsInfo> list) {
        List<TIndicatorsList> vo=new ArrayList<>();
        for (TIndicatorsInfo tIndicatorsInfo : list) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                TIndicatorsList tIndicators=new TIndicatorsList();
                if (StringUtils.isNotEmpty(tIndicatorsInfo.getCIndicatorsType()) && !tIndicatorsInfo.getCIndicatorsType().equals("8") ){
                    BeanUtils.copyProperties(tIndicatorsInfo,tIndicators);
                    List<JsonToPojo> indicators=new ArrayList<>();
                    if (!tIndicatorsInfo.getCIndicatorsName().contains("预警地点")){
                        indicators = objectMapper.readValue(tIndicatorsInfo.getCIndicatorsData(), new TypeReference<List<JsonToPojo>>() {});
                    }else {
                        JsonToPojo jsonToPojo = objectMapper.readValue(tIndicatorsInfo.getCIndicatorsData(), JsonToPojo.class);
                        indicators.add(jsonToPojo);
                    }
                    tIndicators.setIndicators(indicators);
                    tIndicators.setCIndicatorsData(null);
                    vo.add(tIndicators);
                }else {
                    BeanUtils.copyProperties(tIndicatorsInfo,tIndicators);
                    vo.add(tIndicators);
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return vo;
    }

    @Override
    public List<TIndicatorsInfo> rightRegIdTop4(Long id) {

        return indicatorsInfoMapper.rightRegIdTop4(id);
    }

    @Override
    public AlgorithmModelVO statistics(Long safenessId) throws JsonProcessingException {
        List<TIndicatorsInfoVO> infos = indicatorsInfoMapper.selectInfoBysafenessId(safenessId);
        //当前指数
        String dqzs = getVos(infos, "当前指数").getCIndicatorsData();
        String bydf=null;
        //获取6月的分数作为本月得分
        bydf = getString(dqzs, "六月", bydf);
        //预警指数
        String yjzs = getVos(infos,"预警指数").getCIndicatorsData();
        String xydf=null;
        //获取7月的分数作为下月得分
        xydf = getString(yjzs, "七月", xydf);
        //获取5月作为上月得分
        String sydf = getString(dqzs, "五月", bydf);

        // 获取近6个月得分的平均值 和 上一年度对应6个月得分的平均值
        TIndicatorsInfoVO infoVO = infos.get(0);
        SelectAverageBO bo=new SelectAverageBO();
        bo.setYear(infoVO.getYear());
        bo.setCSafenessName(infoVO.getCSafenessName());
        bo.setMonth(infoVO.getMonth());
        bo.setCDistrictId(infoVO.getCDistrictId());
        List<SelectAverageVO> average =tSafenessIndexMapper.selectAverage(bo);


        //获取可借鉴的历史案例
        //预警记录
//        String yjjl = getVos(infos, "预警记录").getCIndicatorsData();
//        StringBuilder anli= new StringBuilder();
//        JSONArray jsonArray=new JSONArray(yjjl);
//        for (int i = 0; i < Math.min(4, jsonArray.size()); i++) {
//            JSONObject object=new JSONObject(jsonArray.get(i));
//            String[] names = object.get("name").toString().split("-");
//            String value = object.get("value").toString();
//            anli.append(String.format("【 %s 】【 %s 】【 %s 】\n", names[0], names.length>1?names[1]:null, value));;
//        }
//        String replaced = anli.toString().replaceAll("\\n$", "");

        //预警地点
        String yjdd = getVos(infos, "预警地点").getCIndicatorsData();;
        PointDataVO pointDataVO = JSON.parseObject(yjdd, PointDataVO.class);
        List<PointData> markPointData = pointDataVO.getMarkPointData();
        StringBuilder yujing= new StringBuilder();
        for (int i = 0; i < Math.min(4, markPointData.size()); i++) {
            String names = markPointData.get(i).getName();
            String value = markPointData.get(i).getScore();
            yujing.append(String.format("【 %s 】得分为【 %s 】\n", names, value));;
        }
        //近6个月平均得分
        Integer averageScore = average.get(0).getAverageScore();
        Integer onAverage=averageScore==null?0:averageScore;
        //去年同期平均得分
        Integer averageScore1 = average.get(1).getAverageScore();
        Integer yearAverage=averageScore1==null?0:averageScore1;
        //本月得分
        String by =bydf==null?"0":bydf;
        //下月得分
        String xy =xydf==null?"0":xydf;
        //上月得分
        String sy =sydf==null?"0":sydf;
        String json = String.format("当前【 %s 】指数出现预警，需持续关注。\n" +
                "该指数本月得分为【 %s 】，预计下月得分为【 %s 】\n" +
                "该指标近6个月平均得分为【 %s 】，去年同期平均得分为【 %s 】\n" +
                "该指标需要重点关注以下区域：\n %s" ,
                infos.get(0).getCSafenessName(),by,xy,onAverage,yearAverage,yujing
        );

        AlgorithmModelVO vo=new AlgorithmModelVO();
        //得分
        vo.setScore(by);
        int scoreStatus = (Integer.parseInt(by) > Integer.parseInt(sy)) ? 1 : ((Integer.parseInt(by) < Integer.parseInt(sy)) ? 2 : 3);
        vo.setScoreStatus(String.valueOf(scoreStatus));
        //同比
        vo.setOnYear(String.valueOf(yearAverage));
        //同比状态
        int onYearType = ( onAverage> yearAverage) ? 1 : ((onAverage < yearAverage) ? 2 : 3);
        vo.setOnYearStatus(String.valueOf(onYearType));
        //环比
        vo.setChainRelativeRatio(xydf);
        int chainRelativeRatioType = (Integer.parseInt(by) > Integer.parseInt(xy)) ? 1 : ((Integer.parseInt(by) < Integer.parseInt(xy)) ? 2 : 3);
        vo.setChainRelativeRatioStatus(String.valueOf(chainRelativeRatioType));
        vo.setDescribe(json);
        vo.setCSafenessName(infos.get(0).getCSafenessName());
        return vo;
    }

    private static String getString(String dqzs, String month, String bydf) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(dqzs);
        // 遍历 JSON 数组
        for (JsonNode node : rootNode) {
            String name = node.get("name").asText();
            if (name.equals(month)) {
                // 找到目标月份，获取其 value 值
               bydf = node.get("value").asText();
            }
        }
        return bydf;
    }

    private static TIndicatorsInfoVO getVos(List<TIndicatorsInfoVO> infos, String name) {
        List<TIndicatorsInfoVO> dqzs = infos.stream().map(item -> {
            if (item.getCIndicatorsName().contains(name)) {
                return item;
            } else {
                return null;
            }
        }).filter(indicator -> indicator != null && !isEmpty(indicator)).collect(Collectors.toList());
        return dqzs.get(0);
    }


}
